<template>
  <div>
    <vxe-grid
      ref="table"
      :class="['table-tree', 'mytable-scrollbar', { isEdit: isEdit }]"
      resizable
      show-overflow
      row-key
      keep-source
      size="small"
      border
      :data="tableData"
      :columns="columns"
      :tree-config="{
        line: true,
        transform: true,
        parentField: 'parentTag',
        rowField: 'tag',
        iconOpen: '',
        iconClose: 'vxe-icon-square-plus',
      }"
      v-bind="isEdit ? vxeOptions : null"
      @edit-actived="editActivedEvent"
    >
      <template #airDryingSubcategory_default="{ row }">
        <template v-if="row.children && row.children.length">
          <i :class="$refs.table.isTreeExpandByRow(row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
        </template>
        <template v-else>
          <i class="vxe-circle"></i>
        </template>
        <span>{{ !row.parentTag ? row.airDryingSubcategory : row.evaluationMode }}</span>
      </template>
      <template #airDryingSubcategory_edit="scope">
        <template v-if="scope.row.children && scope.row.children.length">
          <i :class="$refs.table.isTreeExpandByRow(scope.row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
        </template>
        <template v-else>
          <i class="vxe-circle"></i>
        </template>
        <vxe-input v-if="!scope.row.parentTag" v-model="scope.row.airDryingSubcategory" type="text"></vxe-input>
        <vxe-input v-else v-model="scope.row.evaluationMode" type="text"></vxe-input>
      </template>

      <!-- <template #seq_default="{ row }">
          <span>
            <template v-if="row.children && row.children.length">
              <i
                class="tree-node-icon"
                :class="row.children && row.children.length ? 'vxe-icon-folder-open' : 'vxe-icon-folder'"
              ></i>
            </template>
            <template v-else>
              <i class="vxe-icon-dot"></i>
            </template>
            <span>{{ row.name }}</span>
          </span>
        </template> -->
      <!-- <template #enabledFlag_default="{ row }">
          <span>{{ row.enabledFlag | formatStatus }}</span>
        </template>
        <template #enabledFlag_edit="{ row }">
          <vxe-select v-model="row.enabledFlag" transfer :disabled="isEnabledFlag">
            <vxe-option v-for="item in statuss" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
          </vxe-select>
        </template> -->

      <template #assessmentInstructions_default="{ row }">
        <span>{{ row.assessmentInstructions }}</span>
      </template>
      <template #assessmentInstructions_edit="scope">
        <vxe-input
          v-model="scope.row.assessmentInstructions"
          type="text"
          :disabled="isAssessmentInstructions"
          @change="$refs.table.updateStatus(scope)"
        ></vxe-input>
      </template>

      <template #unit_default="{ row }">
        <span>{{ row.unit }}</span>
      </template>
      <template #unit_edit="scope">
        <vxe-input v-model="scope.row.unit" type="text" :disabled="isUnit"></vxe-input>
      </template>

      <template #lineNumber_default="{ row }">
        <span>{{ row.lineNumber }}</span>
      </template>
      <template #lineNumber_edit="scope">
        <vxe-input
          v-model="scope.row.lineNumber"
          type="text"
          :disabled="isLineNumber"
          @change="$refs.table.updateStatus(scope)"
        ></vxe-input>
      </template>

      <template #operationField_default="{ row }">
        <span>{{ row.operationField }}</span>
      </template>
      <template #operationField_edit="scope">
        <vxe-input
          v-model="scope.row.operationField"
          type="text"
          :disabled="isOperationField"
          :clearable="!isOperationField"
          @click="editEvent(scope.row)"
        ></vxe-input>
      </template>

      <template #dept_default="{ row }">
        <span>{{ row.dept }}</span>
      </template>
      <template #dept_edit="scope">
        <vxe-input v-model="scope.row.dept" type="text" :disabled="isDept"></vxe-input>
      </template>

      <template #operate_item="{ row }">
        <vxe-button v-if="!row.parentTag" type="text" status="primary" @click="add(row, 'bottom')">添加子级</vxe-button>
        <vxe-button type="text" status="danger" @click="del(row)">删除</vxe-button>
      </template>
    </vxe-grid>
    <vxe-modal
      v-model="showEdit"
      title="对应项目运营字段"
      width="800"
      min-width="600"
      height="400"
      resize
      destroy-on-close
      show-footer
    >
      <template #default>
        <vxe-table
          ref="tableOperation"
          class="table-tree"
          resizable
          show-overflow
          row-key
          keep-source
          size="small"
          :row-config="{ isHover: true, isCurrent: true }"
          :tree-config="{
            line: true,
            transform: true,
            iconOpen: '',
            iconClose: 'vxe-icon-square-plus',
          }"
          :data="tableOperationalData"
          :scroll-y="{ enabled: false }"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column tree-node field="field" title="字段">
            <template #default="{ row }">
              <template v-if="row.children && row.children.length">
                <i :class="$refs.table.isTreeExpandByRow(row) ? 'vxe-open_file' : 'vxe-close_file'"></i>
              </template>
              <template v-else>
                <i class="vxe-circle"></i>
              </template>
              <span>{{ row.field }}</span>
            </template>
          </vxe-column>
        </vxe-table>
      </template>
      <template #footer>
        <div class="operation">
          <vxe-button content="取消" @click="showEdit = false"></vxe-button>
          <vxe-button status="primary" content="确认" @click="submit"></vxe-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import Sortable from 'sortablejs';
import XEUtils from 'xe-utils';
import VXETable from 'vxe-table';
export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    columns: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    const validRules = {
      dept: [{ message: '多个部门用英文逗号隔开' }],
    };
    return {
      showEdit: false,
      isEnabledFlag: false,
      isAssessmentInstructions: false,
      isUnit: false,
      isLineNumber: false,
      isOperationField: false,
      isDept: false,
      types: [
        {
          name: '项目商务状态档案',
        },
      ],
      vxeOptions: {
        'row-config': { isHover: true, isCurrent: true },
        'radio-config': { labelField: 'groupName' },
        'scroll-y': { enabled: false },
        'edit-rules': validRules,
        'edit-config': { trigger: 'click', mode: 'row', showStatus: true, showIcon: false },
      },
      selectRow: null,
      tableData: [],
      tableOperationalData: [],
      exportTableData: [],
      mergeCells: [],
      total: null,
    };
  },
  filters: {
    formatStatus(val) {
      return val ? '启用' : '禁用';
    },
  },
  created() {
    //     this.treeDrop()
  },
  mounted() {
    this.getOperationalList();
    this.getList();
  },
  methods: {
    treeDrop() {
      this.$nextTick(() => {
        const $table = this.$refs.table;
        this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ item, oldIndex }) => {
            const options = { children: 'children' };
            const targetTrElem = item;
            const wrapperElem = targetTrElem.parentNode;
            const prevTrElem = targetTrElem.previousElementSibling;
            const tableData = this.tableData;
            const selfRow = $table.getRowNode(targetTrElem).item;
            const selfNode = XEUtils.findTree(tableData, (row) => row === selfRow, options);
            if (prevTrElem) {
              // 移动到节点
              const prevRow = $table.getRowNode(prevTrElem).item;
              const prevNode = XEUtils.findTree(tableData, (row) => row === prevRow, options);
              if (XEUtils.findTree(selfRow[options.children], (row) => prevRow === row, options)) {
                // 错误的移动
                const oldTrElem = wrapperElem.children[oldIndex];
                wrapperElem.insertBefore(targetTrElem, oldTrElem);
                return VXETable.modal.message({ content: '不允许自己给自己拖动！', status: 'error' });
              }
              const currRow = selfNode.items.splice(selfNode.index, 1)[0];
              if ($table.isTreeExpandByRow(prevRow)) {
                // 移动到当前的子节点
                prevRow[options.children].splice(0, 0, currRow);
              } else {
                // 移动到相邻节点
                prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow);
              }
            } else {
              // 移动到第一行
              const currRow = selfNode.items.splice(selfNode.index, 1)[0];
              tableData.unshift(currRow);
            }
            // 如果变动了树层级，需要刷新数据
            this.tableData = [...tableData];
          },
        });
      });
    },
    editActivedEvent({ row, rowIndex }) {
      this.isEnabledFlag = !row.parentTag;
      this.isAssessmentInstructions = !row.parentTag;
      this.isUnit = !row.parentTag;
      this.isLineNumber = !row.parentTag;
      this.isOperationField = !row.parentTag;
      this.isDept = row.parentTag && true;
    },
    async getList() {
      await this.$api
        .ApiLowcostPageList({
          enabledFlag: true,
          page: 0,
          size: 1000,
        })
        .then((res) => {
          try {
            function flatten(arr = [], parent = {}) {
              return arr.reduce(function (prev, item) {
                item.tag = item.id;
                item.parentTag = item.parentId;
                return prev.concat(item, flatten(item.children || [], item));
              }, []);
            }
            this.total = res.total;
            this.tableData = flatten(res.list);
          } catch {}
        });
    },
    async getOperationalList() {
      await this.$api
        .ApiOperationalPageList({
          enabledFlag: true,
          page: 0,
          size: 1000,
        })
        .then((res) => {
          function flatten(arr = [], parent = {}) {
            return arr.reduce(function (prev, item) {
              item.groupName = parent.field;
              return prev.concat(item, flatten(item.children || [], item));
            }, []);
          }
          this.tableOperationalData = flatten(res.list);
        });
    },

    editEvent(row) {
      this.selectRow = row;
      this.showEdit = true;
    },
    async add(currRow, locat) {
      const $table = this.$refs.table;
      const record = {
        tag: Date.now() + '',
        parentTag: currRow.tag,
        field: '',
        evaluationMode: '',
        assessmentInstructions: '',
        unit: '',
        operationField: '',
        dept: '',
      };
      const { row: newRow } = await $table.insertAt(record, -1);
      await $table.setTreeExpand(currRow, true); // 将父节点展开
      await $table.setActiveRow(newRow); // 插入子节点
    },
    async del(row) {
      const $table = this.$refs.table;
      await $table.remove(row);
    },
    submit() {
      const { field, groupName } = this.$refs.tableOperation.getCurrentRecord();
      this.selectRow.operationField = field;
      this.selectRow.groupName = groupName;
      this.showEdit = false;
    },
  },
};
</script>
<style lang="scss">
.mytable-scrollbar {
  .vxe-table--main-wrapper {
    height: calc(100vh - 70px);
    .vxe-table--body-wrapper {
      height: calc(100% - 50px);
    }
  }
}
.table-tree.isEdit {
  .vxe-table--main-wrapper {
    height: calc(100vh - 120px);
    .vxe-table--body-wrapper {
      height: calc(100% - 50px);
    }
  }
}
</style>
